/**
 * Created by chengxm on 2018-04-09.
 */
import { Component, ViewChild } from '@angular/core';
import { GridConfigService } from '@core/config/grid-config.service';

import { extend, missing } from '../../../../utils/utils';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { ApiService } from '@core/services/http/api.service';
import { ApesField } from '@shared/ui-zorro/src/types/apes-field';
import { SubjectService } from '@core/services/events/subject.service';
import { GridOptions } from '@ag-grid-community/core';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';


@Component({
  selector: 'formly-field-grid-table',
  template: `
    <div apes-row [apesGutter]="8">
      <apes-table #basicTable
                  [apesData]="_rowData"
                  [apesShowPagination]="false"
                  class="grid-table"
                  apesBordered>
        <thead>
        <tr>
          <ng-container *ngFor="let col of columnDefs; let i = index;">
            <th class="grid-table-th" [ngStyle]="showStyle(col)">{{col.headerName}}</th>
          </ng-container>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of _rowData; let i = index;">
          <ng-container *ngFor="let col of columnDefs;">
            <ng-container *ngIf="checkDataType(data[col.colId])">
              <td class="grid-table-td">
                <div *ngFor="let d of data[col.colId]">
                  {{formatter(d, getValueFormatter(col))}}
                </div>
              </td>
            </ng-container>
            <ng-container *ngIf="!checkDataType(data[col.colId])">
              <td class="grid-table-td">{{formatter(data[col.colId], getValueFormatter(col))}}</td>
            </ng-container>
          </ng-container>
        </tr>
        </tbody>
      </apes-table>
    </div>
  `,
  host: {},
  styles: [`
    .grid-table {
      margin: 8px;
    }

    .grid-table-th {
      text-align: center;
      padding: 8px 8px;
    }
    .grid-table-td {
      padding: 8px 8px;
    }
  `],
})

export class FormlyFieldGridTable extends ApesField {
  modules: Module[] = AllModules;

  context = {};
  columnDefs: any[];
  _rowData: any[] = [];

  constructor(
    protected events: Events,
    protected expressionService: ExpressionService,
    protected apiService: ApiService,
    protected subject: SubjectService,
  ) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit() {
    this.context['gridName'] = this.key;
    this.context['grid'] = this;
    this.formState['grid_' + this.key] = this;
    this.context = Object.assign(this.context, this.formState);

    /**初始化表头**/
    this.columnDefs = [];

    this.setColumns();

    /**监听表单刷新事件，初始化表格数据**/
    this.subject.subscribe(this.formState, this.subject.event_form_refresh, data => {
      this._rowData = [];
      this.addListener(this.subject.event_form_refresh, data);
      this.getRowData();
    });

  }

  extend(data: any) {
    if (data.constructor === Object) {
      for (let item in data) {
        if (data[item] && data[item].length > 0) {
          return data[item];
        }
      }
    } else {
      return data;
    }
  }

  checkDataType(data) {
    return data instanceof Array;
  }

  showStyle(col){
    let show;
    if(col.hasOwnProperty('width')){
      show = {'width': col.width + 'px'};
    }
    return show;
  }

  /**
   * 功能：重新设置表头
   * @param ctx
   */
  private setColumns() {
    if (!this.to.columnDefs) return;
    this.columnDefs = [];

    this.to.columnDefs.forEach(element => {
      let colDef = extend(true, {}, element);

      colDef.colId = colDef.field;

      this.columnDefs.push(colDef);
    });

    if (this._rowData) {
      this._rowData = this._rowData.length > 0 ? [...this._rowData] : this.model[this.key] == null ? [] : this.model[this.key];
    }
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: this.formState,
      model: this.formState.model,
      value: value,
    });
  }

  getValueFormatter(col): string {
    return col.valueFormatter || 'value';
  }

  /**
   * 功能：初始化表格数据
   * @returns {any}
   */
  private getRowData() {
    /**编辑状态**/
    if (this.formState.states === 'submit') {
      return;
    }
    this._rowData = this.formState.model[this.key] || this.formControl.value || [];
  }

  /**
   * 功能：注册事件监听器
   * @param {string} topic
   * @param value
   */
  private addListener(topic: string, value: any) {
    this.to.columnDefs.forEach(element => {
      let events = element.templateOptions.events;
      if (missing(events)) return;
      events.forEach(em => {
        em.type.split(',').filter(type => type === topic)
          .forEach(type => {
            this.expressionService.evaluate(em.callback, {
              context: this.formState,
              form: this.form,
              model: this.formState.model,
              value: value,
            }, true);
          });
      });
    });
  }

}

